import React, { Component, ReactNode, Fragment } from 'react';
import { Table, message } from 'antd';
import _ from 'lodash';

// eslint-disable-next-line import/no-extraneous-dependencies
import { withRouter } from 'react-router';
import { connect } from 'dva';
import { getBalanceColumns, StateType, PropType } from '../utils';
import { getBalance, memberBalanceRecover, memberBalanceRefresh } from '../service';
import { TRANSFER_PLATFORMS, SUCCESS_CODE } from '../data';
import styles from '../style.less';
import { checkPermission } from '@/utils/resolvePermission';

class MemberBalance extends Component<PropType, StateType> {
  public state: StateType = {
    tableData: {
      list: [],
      total: 0,
    },
    // page: 1,
    // size: 10,
    loading: false,
    balanceList: [],
    countDownSeconds: 10, // 一键回收限制为10s才能执行一次
    hasRecycle: false,
  };

  public timer: any = null; // 定时器

  componentDidMount() {
    this.getList(this.props.id);
  }

  // 获取账户余额
  getList = (id: any) => {
    this.setState({ loading: true });
    getBalance({ userId: id }).then((res: any) => {
      if (res) {
        const { code, data } = res;
        if (code === SUCCESS_CODE && data) {
          const balanceArr: any = [...TRANSFER_PLATFORMS];
          balanceArr.forEach((v: any) => {
            data.forEach((i: any) => {
              if (v.value === i.channelId) {
                v.balance = i.balance;
                v.username = i.username;
              }
            });
          });
          const obj = {};
          _.map(balanceArr, item => {
            obj[item.value.toString()] = item.balance;
          });
          const balanceNumberList: any = [obj, { 0: -1 }];
          this.setState({
            balanceList: balanceArr,
            loading: false,
            tableData: {
              list: balanceNumberList,
              total: data.total,
            },
          });
        }
      }
    });
  };

  // 一键回收
  handleRecycle = () => {
    const { countDownSeconds, hasRecycle } = this.state;
    if (countDownSeconds <= 0 || !hasRecycle) {
      this.recycleTimeDown();
      this.onRecycle()
        .then(() => {
          message.success('回收成功');
        })
        .catch(() => {
          message.error('回收失败');
        });
      this.setState({ countDownSeconds: 10, hasRecycle: true });
    } else {
      message.warn('10s后再点击');
    }
  };

  // 循环调用每个钱包的回收接口
  onRecycle = async () => {
    const { balanceList } = this.state;
    const promises: any = [];
    balanceList.forEach((item: any) => {
      if (item.value === 0) return;
      if (item.balance && Number(item.balance) > 0) {
        promises.push(
          memberBalanceRecover({
            userId: this.props.id,
            channelId: item.value,
          }),
        );
      }
    });

    Promise.all(promises)
      .then(() => {
        this.getList(this.props.id);
      })
      .catch(() => {
        message.error('刷新失败');
        this.getList(this.props.id);
      });
  };

  // 开启定时器
  recycleTimeDown = () => {
    clearInterval(this.timer);
    this.timer = setInterval(() => {
      const { countDownSeconds } = this.state;
      const temp = countDownSeconds - 1;
      this.setState({ countDownSeconds: temp });
      if (temp < 0) {
        clearInterval(this.timer);
      }
    }, 1000);
  };

  // 刷新余额
  refreshBalance = () => {
    this.setState({ loading: true });
    const { balanceList } = this.state;
    const promises: any = [];
    balanceList.forEach((item: any) => {
      if (item.value === 0) return;
      if (item.balance && Number(item.balance) > 0) {
        promises.push(
          memberBalanceRefresh({
            userId: this.props.id,
            channelId: item.value,
          }),
        );
      }
    });

    Promise.all(promises)
      .then(() => {
        this.getList(this.props.id);
      })
      .catch(() => {
        message.error('刷新失败');
      });
  };

  render(): ReactNode {
    const { loading, tableData } = this.state;
    const newTableData = !checkPermission(this.props.btns, 'member-search-recycle')
      ? tableData.list.slice(0, 1)
      : tableData.list;
    console.log(checkPermission(this.props.btns, 'member-search-recycle'));
    console.log(this.props.btns);

    return (
      <Fragment>
        <h3>
          <span>账户余额</span>
          <span className={styles.btn} onClick={this.refreshBalance}>
            刷新余额
          </span>
        </h3>
        <Table
          bordered
          size="small"
          style={{ wordBreak: 'break-all' }}
          rowKey={(record: any, index: number) => String(index)}
          loading={loading}
          columns={getBalanceColumns(this.handleRecycle, this.props.btns, checkPermission)}
          dataSource={newTableData}
          pagination={false}
        />
      </Fragment>
    );
  }
}

// export default MemberBalance;

export default withRouter(
  connect(({ global }: { global: any }) => ({
    btns: global.btns,
  }))(MemberBalance),
);
